import os
from openai import OpenAI
from datetime import datetime
import json
import random

print("DASHSCOPE_API_KEY:", os.getenv("DASHSCOPE_API_KEY"))
client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)

# 模拟天气查询工具。返回结果示例：“北京今天是雨天。”
def get_current_weather(arguments):
    # 定义备选的天气条件列表
    weather_conditions = ["晴天", "多云", "雨天"]
    # 随机选择一个天气条件
    random_weather = random.choice(weather_conditions)
    # 从 JSON 中提取位置信息
    city = arguments["city"]
    # 返回格式化的天气信息
    return f"{city}今天是{random_weather}。"


# 查询当前时间的工具。返回结果示例：“当前时间：2024-04-15 17:15:18。“
def get_current_time():
    # 获取当前日期和时间
    current_datetime = datetime.now()
    # 格式化当前日期和时间
    formatted_time = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
    # 返回格式化后的当前时间
    return f"当前时间：{formatted_time}。"

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_time",
            "description": "获取当前时间",
            "parameters": {}
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "获取指定城市的天气",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "城市名称"
                    }
                },
                "required": ["city"]
            }
        }
    }
]

def get_result(message: str):
    completion = client.chat.completions.create(
        model="qwen-plus",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": message},
        ],
        tools=tools,
        tool_choice="auto",  # 自动选择工具
    )

    message = completion.choices[0].message
    if (message.tool_calls == None):
        return message.content
    
    if (message.tool_calls[0].function.name == "get_current_weather"):
        # 解析工具调用参数
        arguments = json.loads(message.tool_calls[0].function.arguments)
        # 调用天气查询工具
        weather_result = get_current_weather(arguments)
        print("天气查询结果：", weather_result)
        return weather_result
    
    if (message.tool_calls[0].function.name == "get_current_time"):
        # 调用获取当前时间的工具
        current_time_result = get_current_time()
        print("当前时间查询结果：", current_time_result)
        return current_time_result